package com.atguigu.gulimall.member.service.impl;

import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.vo.SocialUser;
import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.dto.MemberRegistDto;
import com.atguigu.gulimall.member.dto.UserLoginDto;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.LoginException;
import com.atguigu.gulimall.member.exception.UserExistException;
import com.atguigu.gulimall.member.service.MemberService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistDto dto) {
        MemberEntity member = new MemberEntity();
        // 设置默认等级
        MemberLevelEntity defaultLevel = memberLevelDao.getDefaultLevel();
        member.setLevelId(defaultLevel.getId());
        // 判断用户名和手机号的唯一性，通过后设置用户名和手机号
        Integer userCount = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", dto.getUserName()));
        if (userCount != 0) {
            throw new UserExistException("用户名已存在，请勿重复注册");
        }
        member.setUsername(dto.getUserName());
        Integer phoneCount = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", dto.getPhone()));
        if (phoneCount != 0) {
            throw new UserExistException("手机号已存在，请勿重复注册");
        }
        member.setMobile(dto.getPhone());
        // 密码进行加密存储
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(dto.getPassword());
        member.setPassword(encode);
        // 设置其他默认信息
        String nickName = "谷粒" + RandomStringUtils.randomAlphanumeric(8);
        member.setNickname(nickName);
        member.setStatus(1);
        member.setCreateTime(new Date());
        baseMapper.insert(member);
    }

    @Override
    public MemberEntity login(UserLoginDto dto) {
        String loginacct = dto.getLoginacct();
        // 校验用户是否存在
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>()
                .eq("username", loginacct).or().eq("mobile", loginacct));
        if (ObjectUtils.isEmpty(memberEntity)) {
            throw new LoginException("该用户不存在，请注册用户后再重新登录。");
        }
        // 校验用户是否启用
        if (memberEntity.getStatus() == 0) {
            throw new LoginException("该用户已被禁用，请联系管理员解除禁用。");
        }
        // 校验密码正确性
        String password = dto.getPassword();
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        boolean checkResult = passwordEncoder.matches(password, memberEntity.getPassword());
        if (!checkResult) {
            throw new LoginException("密码输入错误，请重新输入。");
        }
        return memberEntity;
    }

    @Override
    public MemberEntity oauthLogin(SocialUser socialUser) {
        // 1、判断登录用户是否在谷粒商城系统中存在
        MemberEntity entity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", socialUser.getUid()));
        if (ObjectUtils.isEmpty(entity)) {
            // 若用户在数据库中不存在，则为用户注册一个初始信息的账户
            MemberEntity member = new MemberEntity();
            member.setUsername(socialUser.getUid());
            member.setCreateTime(new Date());
            member.setAccessToken(socialUser.getAccess_token());
            member.setLevelId(5l);
            member.setStatus(1);
            member.setExpiresIn(socialUser.getExpires_in());
            member.setSocialUid(socialUser.getUid());
            // 给用户一个初始密码
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            member.setPassword(passwordEncoder.encode("123456"));
            baseMapper.insert(member);
            return member;
        } else {
            // 若用户存在，则更新用户的access_token和expires_in
            entity.setAccessToken(socialUser.getAccess_token());
            entity.setExpiresIn(socialUser.getExpires_in());
            baseMapper.updateById(entity);
            return entity;
        }
    }
}